#include "widget_image.h"

#include <QtGui/QPainter>
#include <QDir>

WidgetImage::WidgetImage(QWidget* a_Parent, Qt::WFlags a_Flags) : QWidget(a_Parent, a_Flags)
{
	m_Image = NULL;
	m_Data = NULL;
}

WidgetImage::~WidgetImage()
{
	
}

void WidgetImage::Resize()
{
	
}

void WidgetImage::resizeEvent(QResizeEvent* a_Event)
{
	m_StartSize = geometry();

	UpdateDimensions();

	update();
}

void WidgetImage::UpdateDimensions()
{
	float ratio_w = (float)m_StartSize.width() / m_ImageSize.width();
	float ratio_h = (float)m_StartSize.height() / m_ImageSize.height();
	float w, h;

	int start_width = m_StartSize.width();
	int start_height = m_StartSize.height();

	m_Offset.setX(0.f);
	m_Offset.setY(0.f);
		
	if ((int)m_ImageSize.width() > m_StartSize.width())
	{
		if (m_ImageSize.height() > m_ImageSize.width())
		{
			w = m_ImageSize.width() * ratio_h;
			h = (float)m_StartSize.height();

			m_Offset.setX(((float)m_StartSize.width() - (float)w) / 2.f);
		}
		else
		{
			w = (float)m_StartSize.width();
			h = m_ImageSize.height() * ratio_w;

			m_Offset.setY(((float)m_StartSize.height() - (float)h) / 2.f);
		}
	}
	else if ((int)m_ImageSize.height() > m_StartSize.height())
	{
		if (m_ImageSize.width() > m_ImageSize.height())
		{
			w = (float)m_StartSize.width();
			h = m_ImageSize.height() * ratio_w;

			m_Offset.setY(((float)m_StartSize.height() - (float)h) / 2.f);
		}
		else
		{
			w = m_ImageSize.width() * ratio_h;
			h = (float)m_StartSize.height();

			m_Offset.setX(((float)m_StartSize.width() - (float)w) / 2.f);
		}
	}
	else
	{
		w = m_ImageSize.width();
		h = m_ImageSize.height();

		m_Offset.setX(((float)m_StartSize.width() - (float)w) / 2.f);
		m_Offset.setY(((float)m_StartSize.height() - (float)h) / 2.f);
	}

	m_Size.setWidth(w);
	m_Size.setHeight(h);
}

bool WidgetImage::Load(pe::PEImageRaw* a_Image)
{
	if (m_Data) { delete m_Data; }
	m_Width = a_Image->width;
	m_Height = a_Image->height;
	m_Data = new unsigned char[m_Width * m_Height * 4];
	memcpy(m_Data, a_Image->data, m_Width * m_Height * 4);

	if (m_Image) { delete m_Image; }
	m_Image = new QImage(m_Data, a_Image->width, a_Image->height, QImage::Format_ARGB32);

	m_ImageSize.setWidth((float)a_Image->width);
	m_ImageSize.setHeight((float)a_Image->height);
	
	UpdateDimensions();

	m_Clear = false;

	update();

	return false;
}

void WidgetImage::Clear()
{
	m_Clear = true;

	update();
}

void WidgetImage::paintEvent(QPaintEvent* a_Event)
{
	if (!m_Clear && m_Image)
	{
		QPainter painter(this);

		painter.setBrush(QBrush(QColor(0, 0, 0)));

		painter.drawRect(
			QRectF(
				m_Offset.x(), m_Offset.y(), 
				m_Size.width(), m_Size.height()
			)
		);
		painter.drawImage(
			QRectF(
				m_Offset.x(), m_Offset.y(),
				m_Size.width(), m_Size.height()
			), 
			*m_Image, 
			QRectF()
		);
	}
}
